import { CURRENCY_UNIT, CURRENCY_UNIT_ID } from '/@/settings/currencySetting';
import { useCurrencyStore } from '/@/store/modules/currency';
import { useFinanceStore } from '/@/store/modules/finance';
import { useTreeListStore } from '/@/store/modules/treeList';
import { div } from '/@/utils/number';
import { countDecimalPlaces } from '/@/utils/string';
import Big from 'big.js';
import { useI18n } from '/@/hooks/web/useI18n';

Big.NE = -13;
export function getRate() {
  const { getCurrency, getCurrencyMap, getAllCurrencyList } = useCurrencyStore();
  const { getRateObject } = useFinanceStore();
  console.log('当前需要转换成的目标货币名称:', getCurrency);
  const currency = getAllCurrencyList.find((item) => item.name === getCurrency);
  console.log('当前需要转换成的目标货币:', currency);
  const FinanceRates = { ...getRateObject.rates[currency.id], [currency.id]: 1 };
  const FinancegetCurrency = getCurrency;
  return { FinanceRates, FinancegetCurrency, getCurrencyMap, currencyId: currency.id };
}

/**
 *
 * @param number string | number 金额
 * @param currency string 币种名称
 * @returns string 小数位精度 min: 2; max: 配置精度;
 */
export function formatNumberFixed(number, currency) {
  console.log('货币名称：', currency);
  const num = new Big(number);
  const fixed = countDecimalPlaces(CURRENCY_UNIT[currency]);
  const r = num.round(fixed);
  // 按精度舍入后的小数部分

  const decimal = r.toString().match(/\.[0-9]*/);
  return !decimal || (decimal?.length && decimal[0].length < 3)
    ? r.toFixed(2).toString()
    : r.toString();
}

export function createCurrencyData(data?) {
  const { currencyTreeList } = useTreeListStore();
  if (data) {
    return [data, ...currencyTreeList];
  }
  return currencyTreeList;
}

export function calculationAmount(amount: any, currencyId: any) {
  const { FinanceRates } = getRate();
  console.log(FinanceRates[currencyId]);
  const fiexed = countDecimalPlaces(CURRENCY_UNIT_ID[currencyId]);
  const total = Number(div(Number(amount), Number(FinanceRates[currencyId]))).toFixed(fiexed);

  return total;
}

export function getAttrValues(list) {
  console.log(list);
  const { t } = useI18n();
  const attrSet = new Set();

  // Iterate through the list to add attr values to the set
  list.forEach((item) => {
    if (item.attr == 1 || item.attr == 2) {
      attrSet.add(item.attr);
    }
  });
  const result: any = [];

  // Construct the result array based on the presence of attr values
  if (attrSet.has('1')) {
    result.push({ label: t('business.Fiat_currency'), value: 1 });
  }
  if (attrSet.has('2')) {
    result.push({ label: t('business.cryptocurrency_currency'), value: 2 });
  }

  return result;
}
